const App = getApp()
const isMobile = require('../../common/utils/isMobile.js').isMobile
const { API, Ubt, imageHash, User } = App.services
var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置

let timer
let secondsCount = 30
const voiceTypes = ['mobile_voice_first', 'mobile_voice_review', 'mobile_register']

Page({
  data: {
    tabs: ["账号密码登录", "手机验证码登录"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    vertificationStatus: 'idle',
    validate_token: '',
    phone: '',
    editPhone: true,
    sms: '',
    password: '',
    scene: 'login',
    authType: 'sms',
    successUrl: null,
    authing: false,
    remainSeconds: 30,
    pageInited: false,
    wechatCode: '',
    avatarUrl: "/assets/timg.png",
    logIcon: "/assets/logIcon.png",
    pwdIcon: "/assets/pwdIcon.png",
    verifiIcon: "/assets/verifiIcon.png",
    getSmsCodeBtnTxt: "获取验证码",
    getSmsCodeBtnColor: "#0099FF",
    smsCodeDisabled: false,
    loginBtnTxt: "登录",
    loginBtnBgBgColor: "#0099FF",
    btnLoading: false,
    disabled: false
  },
  onLoad: function({
    successUrl,
    scene,
    type,
    phone,
    cartId,
    sig
  }) {
    type = voiceTypes.indexOf(type) === -1 ? 'sms' : 'voice'
    this.setData({
      successUrl: successUrl || false,
      scene: scene || 'login',
      authType: type || 'sms',
      phone: phone || '',
      editPhone: phone ? false : true,
      sig: sig || false,
    })

    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });

    if (phone) {
      if (this.data.isVoice) {
        this.sendCode()
      } else {
        this.setData({
          authing: false
        })
        secondsCount = 30
        this.countDown()
      }
      this.setData({
        pageInited: true
      })
    }
  },

  // 选项卡单击方法
  tabClick: function(e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },

  onUnload: function() {
    // 页面关闭
    if (timer) clearTimeout(timer)
  },
  onShow() {
    var _this = this
    wx.login({
      success: function(res) {
        if (res.code) {
          //发起网络请求
          _this.setData({
            wechatCode: res.code
          })
        } else {
          wx.showToast({
            title: '请允许打开您的微信授权，否则无法正常'
          })
        }
      }
    })
  },

  //如没有openId,则获取openId，获取失败则退出
  successRedirectBymini(mobile) {
    this.setData({
      pageInited: true
    })
    wx.redirectTo({
      url: '/pages/gongzhonghao/index?mobile=' + mobile
    })
  },

  successRedirect() {
    this.setData({
      pageInited: true
    })
    wx.switchTab({
      url: '/pages/retailer/order/order'
    })
  },

  bindPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  bindSMSInput(e) {
    this.setData({
      sms: e.detail.value
    })
  },
  bindPasswordInput(e) {
    this.setData({
      password: e.detail.value
    })
  },

  validatePhone() {
    if (!this.data.phone) {
      wx.showToast({
        title: '请填写手机号'
      })
      return false
    } else if (!isMobile(this.data.phone)) {
      wx.showToast({
        title: '请填写合法的手机号'
      })
      return false
    }
    return true
  },

  alertModal(content = '') {
    wx.showModal({
      title: '提示',
      showCancel: false,
      content,
    })
  },

  sendCode(e) {
    wx.setNavigationBarTitle({
      title: '验证手机号'
    })
    this.getSmsCode()
  },

  sendSMS(e) {
    const phoneValidated = this.validatePhone()
    if (!phoneValidated) return
    this.setData({
      authing: false,
      getSmsCodeBtnColor: "#999",
      smsCodeDisabled: true
    })
    secondsCount = 30

    API.smsCode({
        mobile: this.data.phone,
      })
      .catch(res => {
        wx.hideToast()
        this.alertModal(res.data.message)
        this.setData({
          authing: false
        })
      })
    this.countDown()
  },

  getSmsCode(e) {
    var that = this;
    var count = 30;
    const phoneValidated = this.validatePhone()
    if (!phoneValidated) return
    //发送短信码
    API.smsCode({
      mobile: this.data.phone,
    }).then(res => {
      if (res.data.status != 'success') {
        wx.hideToast()
        this.alertModal(res.data.errorMsg)
        this.setData({
          authing: false
        })
      }
    }).catch(res => {
      wx.hideToast()
      this.alertModal(res.data.message)
      this.setData({
        authing: false
      })
    })

    var si = setInterval(function() {
      if (count > 0) {
        count--;
        that.setData({
          authing: false,
          getSmsCodeBtnTxt: '已发送' + count + ' s',
          getSmsCodeBtnColor: "#999",
          smsCodeDisabled: true
        });
      } else {
        that.setData({
          getSmsCodeBtnTxt: "获取验证码",
          getSmsCodeBtnColor: "#ff9900",
          smsCodeDisabled: false
        });
        count = 60;
        clearInterval(si);
      }
    }, 1000);

  },

  countDown(e) {
    this.setData({
      vertificationStatus: 'sent'
    })
    timer = setTimeout(() => {
      if (secondsCount > 0) {
        secondsCount = secondsCount - 1
        this.setData({
          remainSeconds: secondsCount
        })
        return this.countDown()
      } else {
        this.setData({
          vertificationStatus: 'retrieve',
          remainSeconds: 30
        })
      }
    }, 1000)
  },

  // 使用验证码登录
  formSubmitV(e) {
    //登录前参数检查
    if (!this.validatePhone()) return
    if (!this.data.sms.trim()) {
      return wx.showToast({
        title: '请填写验证码'
      })
    }
    if (!this.data.wechatCode.trim()) {
      return wx.showToast({
        title: '请对微信授权'
      })
    }
    //登录提示
    wx.showToast({
      title: '正在登录',
      icon: 'loading',
      duration: 10000
    })
    this.setData({
      authing: true
    })
    var _this = this
    //登录操作
    API.login({
      mobile: this.data.phone,
      password: null,
      mobileCode: this.data.sms,
      wechatCode: this.data.wechatCode
    }).then(res => {
      if (res.data.status === 'success') {
        wx.hideToast()
        wx.setStorageSync('USER', res.data.result)
        wx.switchTab({
          url:'/pages/home/index'
        })
      } else {
        wx.hideToast()
        this.setData({
          authing: false
        })
        let errmsg = res.data.errorMsg
        wx.showModal({
          content: "登录失败：" + errmsg,
          showCancel: false,
          success: function (mres) {
            if (mres.confirm) {
              console.log('用户点击确定')
            }
          }
        });
      }
    }).catch(res => {
      this.alertModal("登录异常，请重试！")
      wx.hideToast()
      this.setData({
        authing: false
      })
    })
  },

  //使用账号密码登录
  formSubmitN(e) {
    //登录前参数检查
    if (!this.validatePhone()) return
    if (!this.data.password.trim()) {
      return wx.showToast({
        title: '请填写密码'
      })
    }
    if (!this.data.wechatCode.trim()) {
      return wx.showToast({
        title: '请对微信授权'
      })
    }
    //登录提示
    wx.showToast({
      title: '正在登录',
      icon: 'loading',
      duration: 10000
    })

    this.setData({
      authing: true
    })
    var _this = this
    //登录操作
    API.login({
      mobile: this.data.phone,
      password: this.data.password,
      mobileCode: null,
      wechatCode: this.data.wechatCode
    }).then(res => {
      if (res.data.status === 'success') {
        wx.setStorageSync('USER', res.data.result)
        wx.switchTab({
          url:'/pages/home/index'
        })
      } else {
        wx.hideToast()
        this.setData({
          authing: false
        })
        let errmsg = res.data.errorMsg
      }
    }).catch(res => {
      this.alertModal("登录异常，请重试！")
      wx.hideToast()
      this.setData({
        authing: false
      })
    })
  },
})
